package com.ruoyi.mobile.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.mobile.domain.*;
import com.ruoyi.mobile.mapper.*;
import com.ruoyi.mobile.service.SchoolConsumeService;
import com.ruoyi.mobile.utils.*;
import com.ruoyi.mobile.utils.h5.CommenUtil;
import com.ruoyi.mobile.utils.h5.SimpleDateFormatUtil;
import com.ruoyi.mobile.utils.h5.WeChatTemplateMsg;
import com.ruoyi.system.api.req.SchoolConsumeReq;
import com.ruoyi.system.api.resp.SchoolConsumeResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class SchoolConsumeServiceImpl extends ServiceImpl<SchoolConsumeMapper, SchoolConsumeEntity> implements SchoolConsumeService {
    @Autowired
    private SchoolClassesMapper schoolClassesMapper;
    @Autowired
    private ISysDeptMapper sysDeptMapper;
    @Autowired
    private ISysUserMapper sysUserMapper;
    @Autowired
    private SchoolPayrecordMapper schoolPayrecordMapper;

    @Override
    public NftResponse<Paginator<SchoolConsumeResp>> getConsumeList(SchoolConsumeReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        QueryWrapper<SysUserEntity> wrapperUser = new QueryWrapper<>();
        wrapperUser.eq(QueryUtil.camelToUnderline("phonenumber"), query.getPhone());
        wrapperUser.eq(QueryUtil.camelToUnderline("delFlag"),"0");
        wrapperUser.eq(QueryUtil.camelToUnderline("status"), "0");
        List<SysUserEntity> users = sysUserMapper.selectList(wrapperUser);
        QueryWrapper<SchoolConsumeEntity> wrapperQuery = new QueryWrapper<>();
        if (null!=query.getStudentId() && !"".equals(query.getStudentId())) {
            List<Long> studentIds = new ArrayList<>();
            for (SysUserEntity user:users) {
                studentIds.add(user.getUserId());
            }
            wrapperQuery.in(QueryUtil.camelToUnderline("studentId"), studentIds);
        }
        if (null!=query.getTeacherId() && !"".equals(query.getTeacherId())) {
            QueryWrapper<SchoolClassesEntity> wrapperQueryClass = new QueryWrapper<>();
            wrapperQueryClass.and(wrapper -> wrapper.eq(QueryUtil.camelToUnderline("jwteacherId"), query.getTeacherId()).or().eq(QueryUtil.camelToUnderline("jxteacherId"), query.getTeacherId()));
            List<SchoolClassesEntity> classesList = schoolClassesMapper.selectList(wrapperQueryClass);
            List<Long> classesIds = new ArrayList<>();
            for (SchoolClassesEntity obj:classesList) {
                classesIds.add(obj.getId());
            }
            if (null!=classesIds&&classesIds.size()>0) {
                wrapperQuery.in(QueryUtil.camelToUnderline("classesId"), classesIds);
            }else {
                List<Long> teacherIds = new ArrayList<>();
                for (SysUserEntity user:users) {
                    teacherIds.add(user.getUserId());
                }
                wrapperQuery.in(QueryUtil.camelToUnderline("teacherId"), teacherIds);
            }
        }
        Paginator<SchoolConsumeResp> paginator = new Paginator<SchoolConsumeResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        wrapperQuery.inSql("school_id", "select dept_id from sys_dept where app_id='"+query.getAppId()+"'");
        wrapperQuery.orderByDesc("create_time");
        Page<SchoolConsumeEntity> resultPage = this.baseMapper.selectPage(new Page<>(query.getPageNo(),query.getPageSize()),wrapperQuery);
        List<SchoolConsumeResp> pageResult = BeanUtil.copyToList(resultPage.getRecords(), SchoolConsumeResp.class);
        for (SchoolConsumeResp obj:pageResult) {
            SchoolClassesEntity classes = schoolClassesMapper.selectById(obj.getClassesId());
            SysUserEntity teacher = sysUserMapper.selectById(obj.getTeacherId());
            SysUserEntity teacherJw = sysUserMapper.selectById(classes.getJwteacherId());
            SysUserEntity teacherJx = sysUserMapper.selectById(classes.getJxteacherId());
            SysUserEntity student = sysUserMapper.selectById(obj.getStudentId());
            obj.setClassesName(null==classes?"":classes.getClassesName());
            obj.setTeacherNameJw(null==teacherJw?"":teacherJw.getUserName());
            obj.setTeacherNameJx(null==teacherJx?"":teacherJx.getUserName());
            obj.setTeacherName(null==teacher?"":teacher.getUserName());
            obj.setStudentName(null==student?"":student.getUserName());
        }
        paginator.setPageNo(resultPage.getCurrent());
        paginator.setPageSize(resultPage.getSize());
        paginator.setTotalDataNum(resultPage.getTotal());
        paginator.setPageData(pageResult);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<Boolean> insertConsumeInfos(SchoolConsumeReq query) {
        List<Long> xsList = query.getStudents();
        int result = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        for (Long xsId:xsList) {
            SchoolConsumeEntity entity = new SchoolConsumeEntity();
            entity.setSchoolId(query.getSchoolId());
            entity.setClassesId(query.getClassesId());
            entity.setConsumeAmount(query.getConsumeAmount());
            entity.setTeacherId(query.getTeacherId());
            entity.setCreateTime(SimpleDateFormatUtil.getNowDate());
            entity.setStudentId(xsId);
            int rtn = this.baseMapper.insert(entity);
            result = result+rtn;
            QueryWrapper<SchoolPayrecordEntity> wrapperQuery = new QueryWrapper<>();
            wrapperQuery.eq(QueryUtil.camelToUnderline("schoolId"), query.getSchoolId());
            wrapperQuery.eq(QueryUtil.camelToUnderline("studentId"), xsId);
            List<SchoolPayrecordEntity> list = schoolPayrecordMapper.selectList(wrapperQuery);
            BigDecimal amount = BigDecimal.valueOf(0);
            BigDecimal remainder = BigDecimal.valueOf(0);
            Long num = Long.valueOf(0);
            if (null!=list&&list.size()>0) {
                SchoolPayrecordEntity payRecord = list.get(0);
                num = payRecord.getRemaindnum();
                amount = payRecord.getAmount();
                remainder = payRecord.getRemainder();
                remainder = remainder.subtract(entity.getConsumeAmount());
                num -= 1;
                payRecord.setRemainder(remainder.compareTo(BigDecimal.valueOf(0))<0?BigDecimal.valueOf(0):remainder);
                payRecord.setRemaindnum(num<0?0:num);
                schoolPayrecordMapper.updateById(payRecord);
            }
            SysDeptEntity school = sysDeptMapper.selectById(query.getSchoolId());
            SchoolClassesEntity classes = schoolClassesMapper.selectById(query.getClassesId());
            String createDt = format.format(SimpleDateFormatUtil.getNowDate());
            String schoolName = school.getDeptName();
            String classesName = classes.getClassesName();
            this.sendMessage(xsId, createDt, schoolName, classesName, query.getConsumeAmount(), amount, remainder, num, query.getAppId());
        }
        if(result <= 0){
            return new NftResponse<>("200", "耗课失败", false);
        }
        return new NftResponse<>("200", "耗课成功", true);
    }

    private void sendMessage(Long studentId, String createDt, String schoolName,
                             String classesName, BigDecimal consume, BigDecimal amount,
                             BigDecimal remainder, Long num, String appid) {
        SysUserEntity student = sysUserMapper.selectById(studentId);
        String appsecret = AppCode.getValueByKey(appid);
        String access_token = CommenUtil.getInstance().getAccessToken(appid, appsecret);
        String openId = student.getOpenId();// openId代表一个唯一微信用户，即微信消息的接收人
        String templateId = AppTCode.getValueByKey(appid);// 公众号的模板id(也有相应的接口可以查询到)
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        Map<String, WeChatTemplateMsg> sendMag = new HashMap<String, WeChatTemplateMsg>();
        sendMag.put("first", new WeChatTemplateMsg("关于耗课提醒通知"));
        sendMag.put("keyword1", new WeChatTemplateMsg(schoolName));
        sendMag.put("keyword2", new WeChatTemplateMsg(classesName));
        sendMag.put("keyword3", new WeChatTemplateMsg(consume.toString()+"元（价值）"));
        sendMag.put("keyword4", new WeChatTemplateMsg(createDt));
        sendMag.put("keyword5", new WeChatTemplateMsg(student.getUserName()));
        sendMag.put("remark", new WeChatTemplateMsg("总缴费："+amount.toString()+"元（价值），\r\n余额："+remainder.toString()+"元（价值），\r\n剩余次数："+num));
        //拼接base参数
        Map<String, Object> sendBody = new HashMap<>();
        sendBody.put("touser", openId);               // openId
        sendBody.put("template_id", templateId);      // 模板Id
        sendBody.put("data", sendMag);                // 模板参数
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> forEntity = restTemplate.postForEntity(url, sendBody, String.class);
    }
}
